package com.example.doctorstation.shiro;

import com.example.doctorstation.POJOData.User;
import com.example.doctorstation.POJOData.UserRole;
import com.example.doctorstation.Service.RoleServiceImpl;
import com.example.doctorstation.Service.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Victoria-Al
 * @date 2020/7/31
 * 描述：自定义Realm
 **/
public class UserRealm extends AuthorizingRealm {

    /**
     * 负责认证用户身份和对用户进行授权
     */
    @Resource
    private UserServiceImpl userService;

    @Resource
    private RoleServiceImpl roleService;

    // 用户授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<UserRole> roleList = roleService.findByUserId(user.getUserID());
        Set<String> roleSet = new HashSet<>();
        List<String> roleIds = new ArrayList<>();
        for (UserRole role : roleList) {
            roleSet.add(role.getRoleName());
            roleSet.add(role.getRoleId());
            roleIds.add(role.getEMREditorModelD());
        }
        // 放入角色信息
        authorizationInfo.setRoles(roleSet);

        // 放入权限信息
        authorizationInfo.setStringPermissions(new HashSet<>(roleIds));

        return authorizationInfo;
    }

    // 用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authToken;
        User user = userService.findByUserName(token.getUsername());
        if (user == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
